#include "database.h"
#include <iostream>
#include <stdlib.h>

#define FNAME ("database.txt")
/*
file representation
N (the id counter)
start
id:title:id_counter_for_art 
id:title:author:text
..
..
..
start
id:title
X
and so on..
*/

DatabaseDisk::~DatabaseDisk()
{
	map_itr_t	itr;
	for (itr = mymap.begin(); itr != mymap.end(); ++itr)
		delete itr->second;	

	in.close();
	out.close();
}

DatabaseDisk::DatabaseDisk()
{
	string 		s;
	string 		s2;
	string		s3;
	unsigned int 	tmp;
	unsigned int	tmp2;
	NewsGroup * ng = NULL;
	in.open(FNAME);
	/* if there is no file create one */
	if (!in) {
		out.open(FNAME);
		out << "";
		out.close();
		return;
	} 
	if (in.peek() == EOF) {
		in.close();
		return;
	}

	getline(in, s);
	tmp = from_string<unsigned int>(s);
	set_begin_id_number(tmp);
	while (getline(in, s, ':')) {
		if (s == "s") {
			getline(in, s, ':');
			tmp = from_string<unsigned int>(s);
			getline(in, s, ':');
			getline(in, s2);
			tmp2 = from_string<unsigned int>(s2);
			NewsGroup * ng = new NewsGroup(s, tmp, tmp2);
			mymap.insert(make_pair(tmp, ng));
		} else {
			tmp = from_string<unsigned int>(s);
			getline(in, s, ':');
			getline(in, s2, ':');
			getline(in, s3);
			if (ng != NULL)
				ng->add_article(tmp, s, s3, s2); 
		}	
	}

	in.close();
}

void
DatabaseDisk::save_to_disc(void)
{		
	map_itr_t 				itr;
	unsigned int 				tmp;
	map<unsigned int, Article*>::iterator 	a_itr;

	tmp = get_id_number();
	out.open(FNAME);
	out << to_string<unsigned int>(tmp) << endl;

	for (itr = mymap.begin(); itr != mymap.end(); ++itr) {
		out << "s:" << endl;
		tmp = itr->first;
		out << to_string<unsigned int>(tmp) << ":" << 
				itr->second->get_title() << ":" <<
				itr->second->get_art_id_count() << endl;

		for (a_itr = itr->second->begin(); a_itr != itr->second->end();
			++a_itr) {
	
			tmp = a_itr->first;
			out << a_itr->first << ":";
			out << a_itr->second->title << ":";
			out << a_itr->second->author << ":";
			out << a_itr->second->text << endl;
		}
	}

	out.close();
}
void
DatabaseDisk::insert(unsigned int id, NewsGroup* ng)
{
	
	if(mymap.insert(pair<unsigned int, NewsGroup*>(id, ng)).second) {
		save_to_disc();
	}
}


void 
DatabaseDisk::erase(map_itr_t itr)
{
	mymap.erase(itr);	
	save_to_disc();
}

void
DatabaseDisk::update(void)
{
	save_to_disc();
}


